<template>
    <div>
        <el-card shadow="never" style="min-height:500px">
            <!-- header -->
            <el-row style="border-bottom: 1px solid #ebebeb;margin-bottom:20px;padding-bottom:12px;">
                <el-col :span="8">
                    <el-row>
                        <el-col :span="4">
                            <img :src="getAvaterUrl($store.state.custom.avater_url)" style="width:44px;height:44px;border-radius:50%" />
                        </el-col>
                        <el-col :span="12" style="color: #495060;line-height:22px">
                            <el-row style="font-size: 14px;" class="text_ellipsis">{{$store.state.custom.nickname}}</el-row>
                            <el-row style="font-size: 12px">账号：{{$store.state.custom.phone}}
                                <router-link to='/app/account' style="color:#3399ff">设置</router-link>
                            </el-row>
                        </el-col>
                    </el-row>

                </el-col>
                <el-col :span="2" :offset="14" style="text-align:right">
                    <el-button type="primary" size="small" @click="createApplication">创建应用</el-button>
                </el-col>
            </el-row>

            <!-- 应用模版列表 -->
            <el-row style="margin-bottom:12px">
                <el-col :span="20">
                    <div v-for="(item, index) in template" :key="index" style="margin-right:16px;cursor: pointer;line-height: 30px;float:left" class="dot" :class="{ selected: item.id == selectedTemplateId }" @click="searchTemplateId(item.id)">

                        <div class="dot-border" style="border:1px solid;border-radius:50%;width:10px;height:10px;margin-top: 10px;float:left;" :style="{borderColor: item.color, opacity: 0}">&nbsp;</div>
                        <div style="width:10px;height:10px;border-radius:10px;display:inline-block;margin-right:8px;margin-top: 10px;float:left;margin-left:-10px" :style="{backgroundColor: item.color, opacity: 1}">&nbsp;</div>
                        <div style="color:#495060;font-size: 12px;float:left">{{item.name}}</div>
                    </div>
                </el-col>
                <el-col :span="4">
                    <el-input id="searchApp" size="small" v-model="keyword" @keyup.enter.native="search" placeholder="搜索应用" suffix-icon="el-icon-search"></el-input>
                </el-col>
            </el-row>

            <!-- 应用列表 -->
            <el-row v-if="apps.length">
                <el-col :span="6" v-for="(item, index) in apps" :key="index">
                    <el-card shadow="never" style="margin: 6px;border-top:3px solid;height:160px" :style="{borderTopColor: item.template.color}">
                        <el-row style="height:100px;cursor:pointer" @click.native='openApp(item)'>
                            <el-row style="margin-bottom: 10px;">
                                <el-col :span="16" style="font-size: 16px;color: rgb(74, 82, 97);" class="text_ellipsis">{{item.name}}</el-col>
                                <el-col :span="8" style="text-align: right">
                                    <span style="padding: 2px 8px;font-size: 12px;border: 1px solid;" :style="{color:item.template.color}">{{item.template.name}}</span>
                                </el-col>
                            </el-row>

                            <el-row style="color: rgb(128, 138, 151);font-size: 14px;margin-bottom: 10px;">
                                状态：
                                <span v-if="item.status">开启</span>
                                <span v-if="!item.status">关闭</span>
                            </el-row>

                            <el-row style="color: rgb(128, 138, 151);font-size: 14px;margin-bottom: 10px;">
                                有效期：{{getAppValidity(item.started_at, item.ended_at)}}
                            </el-row>
                        </el-row>

                        <el-row v-if="item.wxa.authorizer_appid" style="font-size: 14px;color: rgb(74, 82, 97);cursor:pointer" @click.native="getCreateWxaRedirectUrl(item, '请重新授权小程序')">
                            <el-col :span="22">
                                <img :src="getAvaterUrl(item.wxa.head_img)" style='width: 24px;height: 24px;border-radius: 50%;vertical-align: middle;margin-right: 6px;float:left'>
                                <div style='color: #4a5261;margin-top: 3px;margin-left: 3px;float:left;width:170px' class="text_ellipsis">{{item.wxa.nick_name || '匿名小程序'}}</div>
                            </el-col>
                            <el-col :span="2" style="margin-top:4px">
                                <i class="iconfont icon-shouquan" style="font-size:24px;color: rgb(128, 132, 143)"></i>
                            </el-col>
                        </el-row>
                        <el-row v-if="!item.wxa.authorizer_appid" style="font-size: 14px;color: rgb(74, 82, 97);cursor:pointer" @click.native="getCreateWxaRedirectUrl(item, '当前应用未授权小程序，请授权小程序')">
                            <el-col :span="22">未授权小程序</el-col>
                            <el-col :span="2" style="margin-top:2px">
                                <i class="iconfont icon-shouquan" style="font-size:24px;color: rgb(128, 132, 143)"></i>
                            </el-col>
                        </el-row>
                    </el-card>
                </el-col>
            </el-row>
            <el-row style="text-align:center;margin-top:20px" v-if="apps.length">
                <el-pagination background layout="prev, pager, next" @current-change='changePage' :total="pagination.rowCount" :page-size="pagination.pageSize">
                </el-pagination>
            </el-row>

            <el-row v-if="!apps.length" style="margin: 80px 0;text-align:center">
                <el-col :span="8" :offset="8">
                    <el-row>
                        <i class="el-icon-bell" style="font-size: 93px;color: rgb(51, 153, 255);"></i>
                    </el-row>
                    <el-row style="font-size: 12px;margin-top:12px;color: #495060;">
                        未发现应用，请先
                        <a @click="createApplication">创建应用</a>
                    </el-row>
                </el-col>
            </el-row>
        </el-card>
    </div>
</template>


<script>
import moment from "moment";
export default {
    data() {
        return {
            keyword: "",
            pagination: {
                page: 0,
                pageCount: 0,
                pageSize: 0,
                rowCount: 0
            },
            template: [],
            selectedTemplateId: 0
        };
    },
    async asyncData({ app }) {
        let data = {};

        const template = await app.$axios.$get("/api/app/home/app/template");
        if (template && template.data) {
            template.data.unshift({
                id: 0,
                name: "全部应用",
                color: "#e9eaec"
            });
            data.template = template.data;
        }

        // 获取当前用户的应用
        const apps = await app.$axios.$get("/api/app/home/app/index");
        if (apps && apps.data) {
            data.apps = apps.data.data;
            data.pagination = apps.data.pagination;
        }

        return data;
    },
    methods: {
        createApplication() {
            this.$router.push("/app/template");
        },
        getAppValidity(started_at, ended_at) {
            if (moment(ended_at).isBefore(new Date())) {
                return "已过期";
            }

            const diff = moment(ended_at).diff(moment(started_at), "days");
            if (diff > 30) {
                return `${moment(started_at).format("YYYY/MM/DD")} - ${moment(
                    ended_at
                ).format("YYYY/MM/DD")}`;
            }

            return moment(ended_at)
                .locale("zh-cn")
                .fromNow();
        },
        async getCreateWxaRedirectUrl(item, content) {
            await this.$confirm(content, "温馨提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            });
            this.$cookies.set("AppToken", item.AppToken, {
                path: "/",
                domain: this.getCoryright(),
                maxAge: 60 * 60 * 24 * 7
            });
            const redirect = this.getAppTokenUrl(
                `http://127.0.0.1:3001/app/home/wxa/public/loginReferer?redirect=${encodeURIComponent(
                    `http://www.${this.getCoryright()}/app/apps`
                )}`
            );
            window.open(redirect);
        },
        async searchTemplateId(template_id) {
            let url = `/api/app/home/app/index`;
            if (template_id) {
                url += `?template_id=${template_id}`;
            }

            // 激活
            this.selectedTemplateId = template_id;

            const apps = await this.$axios.$get(url);
            if (apps && apps.data) {
                this.apps = apps.data.data;
                this.pagination = apps.data.pagination;
            }
        },
        async search() {
            let url = `/api/app/home/app/index?keyword=${this.keyword}`;
            if (this.selectedTemplateId) {
                url += `&template_id=${this.selectedTemplateId}`;
            }
            const apps = await this.$axios.$get(url);
            if (apps && apps.errmsg === "ok") {
                this.apps = apps.data.data;
                this.pagination = apps.data.pagination;
            }
        },
        async changePage(page) {
            let url = `/api/app/home/app/index?page=${page}&keyword=${
                this.keyword
            }`;
            if (this.selectedTemplateId) {
                url += `&template_id=${this.selectedTemplateId}`;
            }
            const apps = await this.$axios.$get(url);
            if (apps && apps.errmsg === "ok") {
                this.apps = apps.data.data;
                this.pagination = apps.data.pagination;
            }
        },
        async openApp(item) {
            //应用过期
            // if (moment(item.ended_at).isBefore(new Date())) {
            //     this.$message.warning("该应用已过期");
            //     return;
            // }
            // 删除旧换成
            this.$cookies.remove("AppToken", {
                path: "/",
                domain: this.getCoryright()
            });
            // 设置新的缓存
            this.$cookies.set("AppToken", item.AppToken, {
                path: "/",
                domain: this.getCoryright(),
                maxAge: 60 * 60 * 24 * 7
            });
            if (item.template_id == 2) {
                this.$cookies.set("layout", "diy", {
                    path: "/",
                    domain: this.getCoryright(),
                    maxAge: 60 * 60 * 24 * 7
                });
            }
            if (item.template_id == 1) {
                this.$cookies.set("layout", "shop", {
                    path: "/",
                    domain: this.getCoryright(),
                    maxAge: 60 * 60 * 24 * 7
                });
            }
            this.$cookies.set("header", "首页", {
                path: "/",
                domain: this.getCoryright(),
                maxAge: 60 * 60 * 24 * 7
            });
            this.$router.push("/app/dashboard");
        }
    }
};
</script>


<style scoped>
.dot.selected .dot-border {
    transition: all 0.3s ease;
    transform: scale(1.8);
    opacity: 1 !important;
}
</style><style>
#searchApp {
    border-radius: 16px;
}
</style>
